//extend framework core
sCanvas.fn.extend(true, {
  
  gear: function(x, y, teeth, color, angle, speed, clockwise) {
    var i, toothY, toothAngle, rot,
        radius = teeth * 15 / 2;
    
    //do not repaint canvas during creating gear parts
    this.stopAutorepainting();
    
    //outer circle
    this.circ({
      x: x,
      y: y,
      radius: radius,
      fill: color
    });
    
    //inner circle
    this.circ({
      x: x,
      y: y,
      radius: radius / 4,
      fill: "#fff"
    });
    
    //gear teeth
    toothY = y - radius + 6;
    toothAngle = Math.PI * 2 / teeth;
    
    for (i = 0; i < teeth; i++) {
      this.line(x, toothY)
        .addLine(x - 14, toothY)
        .addLine(x - 9, toothY - 22)
        .addLine(x - 4, toothY - 28)
        .addLine(x + 4, toothY - 28)
        .addLine(x + 9, toothY - 22)
        .addLine(x + 14, toothY)
        .addLine(x, toothY)
        .attr({
          fill: color,
          stroke: null,
          originX: "=" + x,
          originY: "=" + y,
          rotation: i * toothAngle + angle * Math.PI / 180,
          group: "gear gear" + x + y //global group and unique group
        });
    }
    
    //enable autorepainting
    this.startAutorepainting(true);
    
    //fire animation
    rot = (clockwise ? "+=" : "-=") + (2 * Math.PI);
    return this.get("gear" + x + y).animate({ rotation: rot }, {
      duration: speed,
      repeat: Infinity
    });
  }
  
});



new sCanvas("canvas", function() {

//draw gears
var speed = 15000;

this.gear(160, 247, 15, "red", 0, speed, true);
speed *= 4 / 15;
this.gear(131, 413, 4, "#88f", 50, speed, false);
speed *= 41 / 4;
this.gear(355, 698, 41, "green", 1.5, speed, true);
speed *= 6 / 41;
this.gear(661, 477, 6, "#800", 22, speed, false);
speed *= 21 / 6;
this.gear(759, 272, 21, "#088", 8.5, speed, true);
speed *= 11 / 21;
this.gear(528, 140, 11, "blue", 3, speed, false);
speed *= 8 / 11;
this.gear(434, 279, 8, "#f88", 28, speed, true);

//pause/play rotation on click
this.rect(0, 0, this.width(), this.height())
  .attr("fill", null)
  .click(function() {
    if (this.sc.get("gear").isPaused()) {
      this.sc.get("gear").play();
    } else {
      this.sc.get("gear").pause();
    }
  });

});